<template>
  <picker
    mode="multiSelector"
    :range="list"
    @change="pickerChange"
    @columnchange="colChange"
    :range-key="rangeKey"
    @cancel="pickCancel"
    :value="checkVal"
    ><slot></slot
  ></picker>
</template>

<script>
import { apiGetCitys } from '@/api/common'
import cloneDeep from 'lodash-es/cloneDeep'
// 直辖市code
let directly = ['110000', '120000', '310000', '500000']
export default {
  name: 'co-address-picker',
  props: {
    // 省市区code
    value: {
      type: Array,
      default: []
    }
  },
  data() {
    return {
      list: [[], [], []],
      rangeKey: 'name',
      checkVal: [0, 0, 0],
      provinceList: [] // 省列表
    }
  },
  watch: {
    value: {
      handler(n) {
        this.$set(this.list, 1, [])
        this.$set(this.list, 2, [])
        if (n.length === 3) {
          this.getListInit(n)
        } else {
          this.checkVal = [0, 0, 0]
          this.$nextTick(function () {
            this.getCitys()
          })
        }
      },
      immediate: true,
      deep: true
    }
  },
  created() {},
  methods: {
    async cityInit(colNum, checkCode, parentCode) {
      if (colNum === 0 && this.provinceList.length !== 0) {
        let checkIndex = this.provinceList.findIndex(
          (p1) => p1.dm === checkCode
        )
        this.$set(this.checkVal, colNum, checkIndex)
        return
      }
      let isDirect = directly.includes(parentCode)
      let colToLevel = {
        0: '1',
        1: '2',
        2: '3'
      }
      if (colNum === 1 && isDirect) {
        let curObj = this.list[0].find((p1) => p1.dm === this.value[0])
        this.$set(this.checkVal, 1, 0)
        this.$set(this.list, 1, [curObj])
        return
      }
      apiGetCitys({
        level: colToLevel[colNum],
        code: checkCode,
        isDirect: isDirect
      })
        .then((res) => {
          let { data } = res.data
          let checkIndex = data.findIndex((p1) => p1.dm === checkCode)
          if (colNum === 0) {
            this.provinceList = data
          }
          console.log('cityInit checkIndex', checkIndex)
          this.$set(this.list, colNum, data)
          this.$nextTick(function () {
            let checkVal = [...this.checkVal]
            checkVal[colNum] = checkIndex
            this.checkVal = checkVal
            // this.$set(this.checkVal, colNum, checkIndex);
            console.log('checkVal')
            console.log(this.checkVal)
          })
        })
        .catch(() => {
          this.$am_toast.error('查询失败，请重新尝试！')
        })
    },
    /**
     * @param {Number} level [1,2,3]- 查询级别
     * @param {String} parentCode - 上级code
     * @param {Object} curObj - 选中的当前项
     * */
    getCitys(level = 1, parentCode = '', curObj) {
      let isDirect = directly.includes(parentCode)
      switch (level) {
        case 1:
          this.$set(this.list, 1, [])
          this.$set(this.list, 2, [])
          break
        case 2:
          this.$set(this.list, 1, [])
          this.$set(this.list, 2, [])
          break
        case 3:
          this.$set(this.list, 2, [])
          break
      }
      if (level === 1 && this.provinceList.length !== 0) {
        this.getCitys(2, this.provinceList[0].dm, this.provinceList[0])
        return
      }
      if (isDirect && level === 2) {
        this.$set(this.list, 1, [curObj])
        this.getCitys(3, parentCode, true)
        return
      }
      apiGetCitys({ level, code: parentCode, isDirect: isDirect })
        .then((res) => {
          console.log(level, '_++__')
          let data = []
          if (level == 1) {
            res.data.data.forEach((item) => {
              if (item.id == 144) {
                data.push(item)
              }
            })
          } else if (level == 2) {
            res.data.data.forEach((item) => {
              if (item.id == 3461) {
                data.push(item)
              }
            })
          } else {
            data = res.data.data
          }
          switch (level) {
            case 1:
              this.provinceList = data
              this.$set(this.list, 0, data)

              this.getCitys(2, data[0].dm, data[0])
              break
            case 2:
              this.$set(this.list, 1, data)
              this.getCitys(3, data[0].dm, data[0])
              break
            case 3:
              this.$set(this.list, 2, data)
              break
          }
        })
        .catch(() => {
          this.$am_toast.error('查询失败，请重新尝试！')
        })
    },
    pickerChange(e) {
      let colArr = e.detail.value
      console.log('pickerChange col index Arr')
      console.log(colArr)
      if (colArr.length === 3 && colArr.every((p1) => typeof p1 === 'number')) {
        // this.checkVal = [];
        // this.getCitys(1)
        let name = []
        let code = []
        let data = []
        colArr.forEach((p1, p2) => {
          let curObj = this.list[p2][p1]
          data.push(curObj)
          name.push(curObj.name)
          code.push(curObj.dm)
        })
        this.$emit('change', {
          pickerDetail: e.detail,
          code,
          name,
          data
        })
      }
    },
    pickCancel() {
      console.log('picker cancel')
      this.$emit('cancel')
    },
    colChange(e) {
      console.log('picker col change')
      console.log(e.detail)
      let colNum = e.detail.column
      let val = e.detail.value
      let curObj = this.list[colNum][val]
      if (colNum === 0) {
        this.getCitys(2, curObj.dm, curObj)
      } else if (colNum === 1) {
        this.getCitys(3, curObj.dm)
      }
    },
    async getListInit(n) {
      await this.cityInit(0, n[0], '')
      await this.cityInit(1, n[1], n[0])
      this.cityInit(2, n[2], n[1])
    }
  }
}
</script>

<style lang="scss"></style>
